// Joystick.ts
import { _decorator, Component, Node, EventTouch, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Joystick')
export class Joystick extends Component {
    @property(Node)
    joystickBtn: Node = null; // 摇杆按钮

    private maxRadius: number = 100; // 摇杆最大移动半径
    private touchId: number = -1; // 当前触控点ID
    private inputDirection: Vec2 = new Vec2(0, 0); // 输入方向

    onLoad() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    // 触摸开始
    private onTouchStart(event: EventTouch) {
        if (this.touchId === -1) {
            this.touchId = event.getID();
            this.updateJoystickPosition(event);
        }
    }

    // 触摸移动
    private onTouchMove(event: EventTouch) {
        if (event.getID() === this.touchId) {
            this.updateJoystickPosition(event);
        }
    }

    // 触摸结束
    private onTouchEnd(event: EventTouch) {
        if (event.getID() === this.touchId) {
            this.touchId = -1;
            this.resetJoystick();
        }
    }

    // 更新摇杆位置
    private updateJoystickPosition(event: EventTouch) {
        const touchPos = event.getUILocation(); // 获取触摸点屏幕坐标
        const bgWorldPos = this.node.getWorldPosition(); // 摇杆背景的世界坐标
        const localPos = new Vec3(touchPos.x - bgWorldPos.x, touchPos.y - bgWorldPos.y, 0);

        // 限制摇杆移动范围
        const distance = Math.min(localPos.length(), this.maxRadius);
        const direction = localPos.normalize();
        const newPos = direction.multiplyScalar(distance);

        this.joystickBtn.setPosition(newPos);

        // 标准化输入方向（-1到1）
        this.inputDirection.set(newPos.x / this.maxRadius, newPos.y / this.maxRadius);
    }

    // 复位摇杆
    private resetJoystick() {
        this.joystickBtn.setPosition(Vec3.ZERO);
        this.inputDirection.set(0, 0);
    }

    // 获取输入方向（供角色控制器调用）
    public getDirection(): Vec2 {
        return this.inputDirection;
    }
}